<script setup lang="ts">
import { ref } from 'vue'

const display = ref('0')
const operator = ref('')
const previousValue = ref(0)

const handleNumberClick = (num: string) => {
  if (display.value === '0') {
    display.value = num
  } else {
    display.value += num
  }
}

const handleOperatorClick = (op: string) => {
  operator.value = op
  previousValue.value = parseFloat(display.value)
  display.value = '0'
}

const calculate = () => {
  const currentValue = parseFloat(display.value)
  let result = 0
  switch (operator.value) {
    case '+':
      result = previousValue.value + currentValue
      break
    case '-':
      result = previousValue.value - currentValue
      break
    case '*':
      result = previousValue.value * currentValue
      break
    case '/':
      result = previousValue.value / currentValue
      break
  }
  display.value = result.toString()
  operator.value = ''
}

const clear = () => {
  display.value = '0'
  operator.value = ''
  previousValue.value = 0
}
</script>

<template>
  <div>
    <h2 class="text-2xl font-bold mb-4">计算器</h2>
    <div class="bg-gray-100 p-4 rounded mb-4">
      <div class="text-right text-2xl font-mono">{{ display }}</div>
    </div>
    <div class="grid grid-cols-4 gap-2">
      <button v-for="num in [7,8,9,'+',4,5,6,'-',1,2,3,'*',0,'.','=','/']" 
              :key="num"
              class="p-3 bg-blue-500 text-white rounded hover:bg-blue-600"
              @click="num === '=' ? calculate() : 
                      ['+','-','*','/'].includes(num as string) ? handleOperatorClick(num as string) : 
                      handleNumberClick(num.toString())">
        {{ num }}
      </button>
      <button class="col-span-2 p-3 bg-red-500 text-white rounded hover:bg-red-600" @click="clear">
        C
      </button>
    </div>
  </div>
</template>